import React, { Component } from 'react';
import { Redirect, Switch } from 'react-router-dom';

import { Basic } from '@/layout/Basic';
import UserCenter from '@/layout/UserCenter';

import ProgressRouter from './ProgressRoute';

import { Login } from '@/views/login/index';

export class Layout extends Component {
  render() {
    const { location, config } = this.props;
    const { pathname } = location; // pathname = /submenu/menuitem1
    const isLogin = localStorage.getItem('_token')

    let validRouters = []
    config.forEach(v => {
       if (!v.component && v.children.length) {
         v.children.forEach(value => {
          validRouters.push({
            path: v.path + '/' + value.path,
            meta: value.meta,
            component: value.component
          })
         })
       } else {
         validRouters.push({
           path: v.path, 
           component: v.component, 
           meta: v.meta
        })
       }
    })

    const targetRouterConfig = validRouters.find(val => val.path === pathname)

    if (targetRouterConfig) {
      if(!targetRouterConfig?.meta?.auth){
        // basic Layout
        if (pathname === '/login') {
          return <ProgressRouter exact path='/login' component={Login} />
        }
        return <Basic><ProgressRouter exact path={pathname} component={targetRouterConfig.component}/></Basic>
        // return <UserCenter><ProgressRouter exact path={pathname} component={targetRouterConfig.component}/></UserCenter>
      }else{
        // user Layout
        // 已登录
        if (isLogin) {
          return (
            <UserCenter currentPath={pathname}>
              <Switch location={location}>
              {
                validRouters.map(v => <ProgressRouter key={v.path} exact path={v.path} component={v.component}/>)
              }
              </Switch>
            </UserCenter>
          )
        }else{
          // 未登录
          return <Redirect to='/login' />
        }
      }
    }else{
      return <Redirect to='/'/>
    }
  }
}